// pages/meal/meal.js
const tool = require('../../tool/Holidays.js');
const getdata = require("../../tool/GetDate.js")
const util = require("../../utils/util.js")
var app = getApp();
var districtID = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: [],
    weeks: [],
    mealArray: [],
    objectMealArray: [],
    multiIndex: [1, 1, 1],
    diningHallArray: [],
    objectDiningHallArray: [],
    index: 0,
    message: "",
    districtArray: [],
    objectDistrictArray: [],
    districtIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.myUserData);
    try {
      if (app.globalData.myUserData.userID) {
        this.refreshHolidays();
      } else {
        wx.reLaunch({
          url: '/pages/user_registration/user_registration',
        })
      }

      //获取区域信息
      this.getDistrict();

      this.getMeal(app.globalData.myUserData.districtID);

      //刷新点餐信息（区域参数只是用来获取数据库，所以只要本公司的区域都行）
      this.refreshMeal(app.globalData.myUserData.districtID);

    } catch { }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // var a = this.getStandardFestivals("",)
    // console.log();

  },

  getDistrict: function () {
    let that = this;
    getdata.getdata({
      url: "gbt/BasicInfo/DistrictInfo/",
      data: app.globalData.myUserData.districtID,
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          let districtIndex = wx.getStorageSync("districtIndex");
          if (!districtIndex) {
            districtIndex = 0;
          }

          districtID = res.root.districtArray[districtIndex].id;
          that.getDiningHall(districtID);
          // //刷新节假日
          // that.refreshHolidays();
          
          that.setData({
            districtArray: res.root.districtTitleArray,
            objectDistrictArray: res.root.districtArray,
            districtIndex: districtIndex,
          });
        }
      },
    });
  },

  getDiningHall: function (districtID) {
    let that = this;
    //根据获取到的区域信息加载食堂
    getdata.getdata({
      url: "gbt/BasicInfo/DiningHall/",
      data: districtID,
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          let diningHallIndex = wx.getStorageSync("diningHallPickerIndex");
          if (!diningHallIndex) {
            diningHallIndex = 0;
          }

          that.setData({
            diningHallArray: res.root.diningHallTitleArray,
            objectDiningHallArray: res.root.diningHallArray,
            index: diningHallIndex,
          });
        }
      },
    });
  },

  getMeal:function(districtID){
    let that = this;
    //根据获取到的区域信息加载餐点
    getdata.getdata({
      url: "gbt/BasicInfo/Meal/",
      data: districtID,
      success: function (res) {
        console.log(res.root);
        if (res.root) {
          let mealIndex = wx.getStorageSync("mealPickerIndex");
          if (!mealIndex) {
            mealIndex = [1, 1, 1];
          }

          that.setData({
            mealArray: res.root.mealTitleArray,
            objectMealArray: res.root.mealObjectArray,
            multiIndex: mealIndex,
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  refreshHolidays:function(){
    let that = this;
    tool.localHolidays({
      success: function (res) {
        console.log(res);
        that.setData({
          date: res.date,
          weeks: res.weeks,
        });
        //date数据写入缓存
        wx.setStorage({
          key: 'nowDate',
          data: res.date,
        });
      }
    });
  },

  refreshMeal: function (districtID) {
    let that = this;
    let param = {};
    param.userID = app.globalData.myUserData.userID;
    param.districtID = districtID;

    getdata.postdata({
      url: "gbt/Meal/MealAllHallReport",
      data: JSON.stringify(param),
      success: function (res) {
        console.log(res.root.data);
        if (res.root) {
          let date = that.data.date;
          let mealArray = res.root.data;
          let day = [];
          let mealDate = "";

          for (let dateIndex = 0; dateIndex < date.length; dateIndex++) {
            day = date[dateIndex];
            for (let dayIndex = 0; dayIndex < day.length; dayIndex++) {
              for (let mealIndex = 0; mealIndex < mealArray.length; mealIndex++) {
                mealDate = mealArray[mealIndex].date.replace("T00:00:00", "");
                if (mealDate === day[dayIndex].re) {
                  day[dayIndex].selected = 1;
                  day[dayIndex].holidayName = mealArray[mealIndex].shortName;
                  day[dayIndex].name = mealArray[mealIndex].amount;
                  date[dateIndex] = day;
                }
              }
            }
          }
          that.setData({
            date: date,
          });
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log(app.globalData.myUserData);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  bindDistrictPickerChange: function (e) {
    this.setData({
      districtIndex: e.detail.value
    })
    let district = this.data.objectDistrictArray[e.detail.value];
    districtID = district.id;
    this.getDiningHall(districtID);
    //刷新点餐信息
    this.refreshMeal(districtID);
    wx.setStorageSync("districtIndex", e.detail.value);
    wx.setStorageSync("diningHallPickerIndex", 0);
  },

  bindMealPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)

    this.setData({
      multiIndex: e.detail.value
    })
    wx.setStorageSync("mealPickerIndex", e.detail.value);
  },

  bindDiningHallPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    });
    wx.setStorageSync("diningHallPickerIndex", e.detail.value);
  },

  selectday: function (e) {
    let date = this.data.date;
    let date_day = date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].re.replace("-", "/").replace("-", "/");
    console.log(this.data.date[e.currentTarget.dataset.index][0].month);
    console.log(date_day);
    console.log(e.currentTarget.dataset);
    console.log(util.formatTime(new Date()));
    //控制时间 过后由服务端提供
    let time = ' 17:30:00';//服务器为提供食堂截止时间，则使用默认时间
    if(this.data.objectDiningHallArray[this.data.index].deadline){
      time = ' ' + this.data.objectDiningHallArray[this.data.index].deadline;
    }
    console.log(util.formatDateDiff(0) + time);
    console.log(util.formatDateDiff(-1) + time);
    if (util.formatTime(new Date()) > util.formatDateDiff(-1) + time && date_day === util.formatDateDiff(0)) {
      this.setData({
        message: `[${util.formatShortTime(new Date())}]：超过${util.formatDateDiff(-1) + time}，你无法更改${util.formatDateDiff(0)}报餐信息。`
      });
      return;
    }
    if (util.formatTime(new Date()) > util.formatDateDiff(0) + time && date_day === util.formatDateDiff(1)) {
      this.setData({
        message: `[${util.formatShortTime(new Date())}]：超过${util.formatDateDiff(0) + time}，你无法更改${util.formatDateDiff(+1)}的报餐信息。`,
      });
      return;
    }
    let that = this;
    // let date = this.data.date;
    let holiday = date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].holiday;
    let selected = date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].selected;
    if (holiday == 2 && selected === 0) {
      wx.showModal({
        title: '温馨提示',
        content: "你选择的日期" + date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].re + "为" + date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].holidayFullName + "休息期间，需要报餐吗？",
        success: function (res) {
          if (res.confirm) {
            if (selected === 0) {
              date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].selected = 1;
            } else {
              date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].selected = 0;
            }

            //更新报餐信息
            let dataset = e.currentTarget.dataset;
            that.mealOpt(dataset);
          }
          that.setData({
            date: date,
          });

        }
      });

    } else {
      if (selected === 0) {
        date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].selected = 1;
      } else {
        date[e.currentTarget.dataset.index][e.currentTarget.dataset.indexs].selected = 0;
      }

      that.setData({
        date: date,
      });

      //更新报餐信息
      let dataset = e.currentTarget.dataset;
      that.mealOpt(dataset);
    }
  },

  //长按日历里面的日期
  selectLongDay:function(e){

  },

  //报餐操作 即时更新报餐信息
  mealOpt: function (dataset) {
    let that = this;
    let date = this.data.date;
    let selected = date[dataset.index][dataset.indexs].selected;
    let mealItem = [];
    let paramDateItem = {};
    let paramDateArray = [];
    let param = {};
    let isAdd = true; //是否添加参数数据

    for (let mealIndex = 0; mealIndex < this.data.objectMealArray.length; mealIndex++) {
      mealItem = this.data.objectMealArray[mealIndex]; //遍历用户选择的餐点
      for (let mealItemIndex = 0; mealItemIndex < mealItem.length; mealItemIndex++) {
        for (let index = 0; index < this.data.multiIndex.length; index++) {
          paramDateItem = {};
          if (mealItem[mealItemIndex].id == this.data.multiIndex[index] && mealIndex == index && this.data.multiIndex[index] == 1) {
            isAdd = false; //取到用户选择的餐点 则记录并跳出循环
            paramDateItem.userID = app.globalData.myUserData.userID;
            paramDateItem.hallID = this.data.objectDiningHallArray[this.data.index].id;
            paramDateItem.date = date[dataset.index][dataset.indexs].re;
            paramDateItem.mealID = mealItem[mealItemIndex].mealId;
            paramDateItem.dayIndex = dataset.indexs;
            paramDateItem.month = date[dataset.index][dataset.indexs].month;
            paramDateItem.qty = 1;
            paramDateItem.districtID = districtID;
            paramDateItem.state = "Add";
            paramDateItem.name = mealItem[mealItemIndex].name;
            paramDateArray.push(paramDateItem);
          } else if (mealItem[mealItemIndex].id == this.data.multiIndex[index] && mealIndex == index && this.data.multiIndex[index] == 0) {
            isAdd = false; //取到用户选择的餐点 则记录并跳出循环
            paramDateItem.userID = app.globalData.myUserData.userID;
            paramDateItem.hallID = this.data.objectDiningHallArray[this.data.index].id;
            paramDateItem.date = date[dataset.index][dataset.indexs].re;
            paramDateItem.mealID = mealItem[mealItemIndex].mealId;
            paramDateItem.dayIndex = dataset.indexs;
            paramDateItem.month = date[dataset.index][dataset.indexs].month;
            paramDateItem.qty = 1;
            paramDateItem.districtID = districtID;
            paramDateItem.state = "Del";
            paramDateItem.name = mealItem[mealItemIndex].name;
            paramDateArray.push(paramDateItem);
          }
          //添加到参数就跳过改循环
          if (!isAdd) {
            break;
          }
        }
        isAdd = true;
      }
    }
    param.meal = paramDateArray;
    console.log("报餐参数");
    console.log(param);
    //更新数据
    getdata.postdata({
      url: "gbt/Meal/AddMeal",
      data: JSON.stringify(param),
      success: function (res) {
        console.log(res.root);
        // wx.showModal({
        //   title: '温馨提示',
        //   content: `${res.root.message}`,
        //   showCancel: false,
        // })

        //初始化日期
        let oldDate = wx.getStorageSync("nowDate");
        that.setData({
          date: oldDate,
          message: `${res.root.message}`,
        })
        //操作点餐后及时刷新点餐信息
        that.refreshMeal(districtID);
      }
    });
  },

  onConfirm: function () {
    console.log("订阅报餐提醒");
    wx.requestSubscribeMessage({
      tmplIds: ['1L5a_xdZW3jeggkOV7N03Mbrzzg4E4Ql9OE6ZHtY-xs'],
      success(res) {
        console.log("返回结果");
        console.log(res);

      }
    })
  },

  onHelp:function(){
    wx.showModal({
      title: '帮助',
      content: '1、选择食堂和餐点，再点击日期，可完成报餐\n2、选择食堂和餐点，再点击已报餐的日期，可覆盖报餐\n3、选择食堂，全部餐点都不选，点日期，可撤销一整天的报餐\n4、选择餐点：点开选择餐点，把不需要报餐的餐点往下拉，点确定即可',
      showCancel: false,
    })
  },
})
